<template>
  <div id="login">
<!--    <img src="/res/fanhui.svg" style="width: 24px;margin-top: 14px;margin-left:14px;cursor: pointer;" @click="subDl()" title="返回账号秘密登录">-->
    <div class="logo">
      <div style="text-align:center;margin-top: 30px;">
        <img src="./theme/images/logo.svg" style="width:200px;"/>
      </div>
    </div>
    <div class="content">
      <div>
        <el-form ref="model" :model="model" v-loading="loading" element-loading-text="正在登录，请稍等">

          <el-form-item prop="dh" :rules="[{ required: true, message: '请输入手机号'}]">
            <el-input type="text" v-model="model.dh" size="small" placeholder="请输入手机号"
                      prefix-icon="el-icon-mobile-phone" style="margin-top: 4.68px;"
                      clearable></el-input>
          </el-form-item>
          <elm-row>
            <el-form-item prop="yzm" :rules="[{ required: true, message: '请输入验证码'}]">
              <el-input type="text" v-model="model.yzm" size="small" placeholder="请输入验证码" style="margin-top: 15px;" clearable></el-input>
            </el-form-item>
            <el-button :type="buttonType" style="flex: 0 1 10%; height: 37px;margin-top: 18px;" size="small" :disabled="isDisabled" @click="getYZM()">{{ buttonText }}</el-button>
          </elm-row>
          <el-form-item prop="qymc" :rules="[{ required: true, message: '请输入企业名称'}]">
            <el-input type="text" v-model="model.qymc" size="small" placeholder="请输入企业名称"
                      prefix-icon="el-icon-office-building" style="margin-top: 15px;" clearable></el-input>
          </el-form-item>
          <template v-if="model.msg!=''">
            <span style="color:red;line-height:30px;padding-left:5px;">{{ model.msg }}</span>
          </template>
          <div style="text-align: right;margin-right: 7px; ">
<!--            <span style="color: rgb(122,126,134);">马上体验?&nbsp;&nbsp;</span>-->
            <span @click="opensub()"
                  style="color: rgb(12,115,254);font-size:16px;text-decoration: underline;text-underline-offset: 0.1em;cursor: pointer">
              已有账号登录</span></div>
          <el-form-item>
            <el-button class="tj" type="primary" @click="submit" size="small" style="width: 100%; margin-top: 20px; line-height: 22px;font-size:16px;margin-bottom: 10px;">登&nbsp;录
            </el-button>
          </el-form-item>
        </el-form>
        <elm-dialog ref="dialog"></elm-dialog>
      </div>
    </div>
    <div class="copyright"></div>
  </div>
</template>
<script>
export default {
  extends: elmVueBase,
  data() {
    return {
      loading: false,
      model: {dh: '', yzm: '',qymc:'', msg: ''},
      enc_yzm:null,
      isDisabled: false,
      buttonText: "获取验证码",
      buttonType: 'primary',
      countdownTime: 60,
      countdownEndTime: null,
    }
  },
  created() {
    this.checkCountdown();
  },
  methods: {
    opensub() {
      this.$parent.loginType = "";
    },

    async submit() {
      await this.$refs["model"].validate();
      if(!this.validatePhoneNumber(this.model.dh))
      {
        this.model.msg = "手机号输入错误。";
        this.loading = false;
        return;
      }
      this.loading = true;
      let res = await elm.post("/system/login/FreeLogin", {
        dh: this.model.dh,
        yzm: this.model.yzm,
        qymc: this.model.qymc,
        enc_yzm:this.enc_yzm
      });
      if (res.success == true) {
        elm.info.token = res.token;
        elm.info.tenant = "free";
        elm.info.system = res.system;
        elm.info.menu = res.menu;
        elm.info.user = res.user;
        elm.info.org = res.org;
        elm.info.role = res.role;
        location.href = elm.settings.routefix + elm.info.system.path;
      } else if (res.success == false || res.status == 401) {
        if(res.msg)
        {
          this.model.msg = "验证码错误。";
        }
        else {
          this.model.msg = "登录失败，请稍后重试。";
        }
      } else {
        this.model.msg = "登录失败，请稍后重试。";
      }
      this.loading = false;
    },
    async getYZM()
    {
      if(!this.validatePhoneNumber(this.model.dh))
      {
        this.model.msg = "手机号输入错误。";
        return;
      }
      this.isDisabled = true;
      this.buttonType='info';
      let res = await elm.post("/system/login/FreeYZM", {
        dh: this.model.dh
      });
      if(res.yzm)
      {
        this.v("验证码已发送。")
        this.enc_yzm=res.yzm;
        // 禁用按钮并开始倒计时

        this.countdownEndTime = Date.now() + this.countdownTime * 1000;
        this.startCountdown();

        // 保存倒计时结束时间到 localStorage
        localStorage.setItem("countdownEndTime", this.countdownEndTime);
      }
    },
    startCountdown() {
      const countdownInterval = setInterval(() => {
        const remainingTime = this.countdownEndTime - Date.now();

        if (remainingTime <= 0) {
          clearInterval(countdownInterval);
          this.isDisabled = false;
          this.buttonText = "获取验证码";
          this.buttonType='primary';
        } else {
          this.buttonType='info';
          this.buttonText = `重新发送(${Math.ceil(remainingTime / 1000)}s)`;
        }
      }, 1000);
    },
    checkCountdown() {
      const storedEndTime = localStorage.getItem("countdownEndTime");
      if (storedEndTime) {
        const remainingTime = parseInt(storedEndTime, 10) - Date.now();

        if (remainingTime > 0) {
          this.isDisabled = true;
          this.countdownEndTime = parseInt(storedEndTime, 10);
          this.buttonType='info';
          this.buttonText = `重新发送(${Math.ceil(remainingTime / 1000)}s)`;

          // 继续倒计时
          this.startCountdown();
        } else {
          // 倒计时已结束，清理 localStorage
          localStorage.removeItem("countdownEndTime");
        }
      }
    },
    validatePhoneNumber(phoneNumber) {
      // 检查是否为空
      if (!phoneNumber) {
        return false;
      }
      // 检查是否包含空格
      if (/\s/.test(phoneNumber)) {
        return false;
      }
      if (phoneNumber==null) {
        return false;
      }

      // 检查长度
      if (phoneNumber.length !== 11) {
        return false;
      }

      // 检查是否全为数字
      if (!/^\d+$/.test(phoneNumber)) {
        return false;
      }

      // 检查开头数字
      const firstDigit = phoneNumber.charAt(0);
      if (firstDigit !== '1') {
        return false;
      }

      // 检查第二位数字
      const secondDigit = phoneNumber.charAt(1);
      const validSecondDigits = ['3', '4', '5', '7', '8'];
      if (!validSecondDigits.includes(secondDigit)) {
        return false;
      }

      // 检查是否重复数字
      const uniqueDigits = new Set(phoneNumber);
      if (uniqueDigits.size === 1) {
        return false;
      }

      // 检查特定前缀（可选）
      const specificPrefixes = ['130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '150', '151', '152', '153', '155', '156', '157', '158', '159', '170', '171', '172', '173', '175', '176', '177', '178', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189'];
      if (!specificPrefixes.some(prefix => phoneNumber.startsWith(prefix))) {
        return false;
      }

      // 所有检查通过
      return true;
    }

  }
};
</script>

<style scoped>
@import url('theme/login.css');
.login .el-form-item {
  border: 0px solid #EBEEF5 !important;
}
#login
{
  background-color: rgba(255,255,255,0.8);
  border-radius: 12px;
  box-shadow: 0 0px 15px 0 rgba(0,39,87,0.2) ;
  width: 370px;
}
#login .content {
  background: rgba(125,218,255,0.0);
  width: 350px;
}
.el-button.tj {
  background: rgb(3,138,255) !important;
  color: rgb(255,255,255) !important;
  border: 0px solid #EBEEF5 !important;
}

.el-button.tj:hover {
  background: rgba(3,138,255,0.8) !important;
  color: rgb(255,255,255) !important;
  border: 0px solid #EBEEF5 !important;
}

.el-form {
  border: 0px solid #EBEEF5;
}

</style>